package com.atsmart.app.webservice;

import java.io.IOException;

import android.os.AsyncTask;
import android.util.Log;

import com.atsmart.app.exception.BizException;
import com.atsmart.app.utils.PersistentKeyUtil;
//import com.atsmart.log.UserLog;
import com.google.json.JsonParseException;

/**
 * AsyncTask:。这种结构将所有的线程通信都封装成回调函数，调用逻辑容易书写。
 * 其调用关系为：execute（）向doInBackground（）传递。 　
 * doInBackground()的返回值会传递给onPostExecute()。
 * publishProgress()向progressUpdate（）传递。
 */
public abstract class ServiceAsynTask<T> extends AsyncTask<Void, Void, T> {
	private int errorCode = -1;

	public ServiceAsynTask() {
		super();
	}

	protected abstract T callService() throws IOException, JsonParseException, AssertionError,
			BizException,Exception;

	protected abstract void runWithResult(T result) throws Exception;

	protected abstract void runWithError(T result, int iErrorCode) throws Exception;

	@Override
	protected T doInBackground(Void... params) {
		try {
			return callService();
		}catch (Exception e) {
//			e.printStackTrace();
			//System.out.println(e);
//			UserLog.getInstance().write(e.getMessage());
			errorCode = PersistentKeyUtil.NETWORK_ERROR;
		}
		return null;
	}

	protected void onPostExecute(T result) {
		if (errorCode == -1) {
			try {
				runWithResult(result);
			} catch (Exception e) {
			}
		} else {
			try {
				runWithError(result, errorCode);
			} catch (Exception e) {
			}
		}

	}

}
